from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
from django.template import Template, Context
from django.template import RequestContext
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db import transaction
import csv, os
from tempfile import TemporaryFile
from catalog.models import *
import time
import re
from django.core import serializers
from django.utils import simplejson



def depList(request,
            template_name='catalog/index.html'):
    
    objs = cClass.objects.all().order_by('dept')
    deps = ["%s"%d.dept for d in objs]
    dep = set(deps)
    dep = list(dep)
    dep.sort()
    return render_to_response(template_name,
                                  {'depList':dep},
                        context_instance=RequestContext(request)) 
                        
def byDep(request,
          department,
          template_name='catalog/clist.html'):
    objs = cClass.objects.filter(dept = department)
    print objs
    #A fast,sneaky way of putting the two lists together
    courses =[(crs,cls) for cls in objs for crs in cls.course_set.all()]
    print courses
    return render_to_response(template_name,
                                  {'classes':courses,'heading':department},
                        context_instance=RequestContext(request))
                        
def byTime(request,
           time,
           template_name='catalog/clist.html'):
    objs = Course.objects.filter(Btime = time)       
    print objs
    courses =[(crs, crs.supclass)for crs in objs]
    print courses
    return render_to_response(template_name,
                                  {'classes':courses,'heading':time},
                        context_instance=RequestContext(request))       

def listTimes(request,
            template_name='catalog/listTimes.html'):
    objs = Course.objects.all()
    times = ["%s"%d.Btime for d in objs]
    times = set(times)
    times = list(times)
        
    #e = time.strptime("08:00:00 AM", "%I:%M:%S %p")
    #print e.strftime("%I:%M:%S %p")
    times.sort()
    print times
    return render_to_response(template_name,
                                  {'timeList':times},
                        context_instance=RequestContext(request))    
                        
                        
#<span><a href="{% url listgeneds%}">General Education Classes.</a></span>
def listGeneds(request,
               template_name='catalog/genEd.html'):
    objs = cClass.objects.all().order_by('dept')
    gen = []
    areas = set()
    gepat = 'G\w{2}\d$'
    gee =[]
    for i in objs:
        m = re.search(gepat, i.title)
        if m:
            print m.group(0)
            areas.add(m.group(0))
            gen.append(i)
            gee.append((m.group(0),i))
    def lpat(pat):
        l = []
        for c in gen:
            m = re.search(pat, c.title)
            if m:
                for i in c.course_set.all():
                    l.append((c,i))
        return l
    l= [(a,lpat(a))for a in areas]
    return render_to_response(template_name,
                                  {'classes':l},
                        context_instance=RequestContext(request))
           
def addevent(request):
    def tform(t):
        m = re.split(':\d{2} (PM|AM)', t, 1)
        m = "%s %s" %(m[0], m[1])
        return m
    def makeEvent():
        course = Course.objects.get(id = cid)
        return {"id":course.id,"days":course.days
            ,"starttime": tform(course.Btime)
            ,"endtime": tform(course.Etime)
            , "title":"%s" %(course.supclass)}
        
    cid = request.REQUEST['courseid']
    if not request.session.get('events',0) == 0:
        #get json out of session var, turn inot python objs
        prevent = request.session['events']
        oldevents = simplejson.loads(prevent)
        #check to see if we are adding the same course;
        def checkSession():
            for i in oldevents:
                print i['id'] 
                if(i['id']==cid):
                    return False
                else:
                    return True
                    
        if checkSession():
            oldevents.append(makeEvent())
            data =  simplejson.dumps(oldevents)
        else:
            data = simplejson.dumps(oldevents)
              
    else:
        eventslist = []
        eventslist.append(makeEvent())
        data =  simplejson.dumps(eventslist)        
    response = HttpResponse(data, mimetype='application/json')   
    request.session['events']=data
    request.session.save()
    for i in simplejson.loads(data):
        print i
    return response
  
def events(request):
    response = HttpResponse(request.session['events'], mimetype='application/json')   
    return response

    
